package com.ticket.sass.admin.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.dto.input.member.MemberCardListInput;
import com.ticket.sass.admin.mapper.MemberCardMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.MemberCardEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 会员卡 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-06
 */
@Service
public class MemberCardServiceImpl extends ServiceImpl<MemberCardMapper, MemberCardEntity> implements BaseService<MemberCardEntity> {
    public IPage<MemberCardEntity> iPage(MemberCardListInput input) {
        Page<MemberCardEntity> page = new Page<>(input.getPageNum(), input.getPageSize());
        QueryWrapper<MemberCardEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(input.getCellphone()), "u.cellphone", input.getCellphone());
        queryWrapper.orderByDesc("c.id");
        
        queryWrapper.isNull("u.deleted_at");
        queryWrapper.isNull("c.deleted_at");
        return this.baseMapper.queryPage(page, queryWrapper);
    }
    
    public MemberCardEntity getOneByUserId(Long userId) {
        return findBy(userId, "user_id");
    }
    
    /**
     * 将金额退回到会员卡
     *
     * @param amount 退回的金额
     */
    public void refundToCard(MemberCardEntity memberCard, BigDecimal amount) {
        // 计算新的余额
        BigDecimal newBalance = memberCard.getBalance().add(amount);
        
        // 创建 UpdateWrapper 并设置更新条件和更新内容
        UpdateWrapper<MemberCardEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", memberCard.getId()).set("balance", newBalance);
        
        // 执行更新操作
        update(updateWrapper);
    }
    
}
